<template>
	<view>
		<view class="reday" v-if="banner" :style="{top:top+'px'}">
			<view class="loading-img" v-if="loading">
				<u-loading></u-loading>
			</view>
			<image :src="readyImgURL" mode="aspectFill" @load="load"></image>
			<view class="btn" @click="jump" :style="{
				top:btnOffset+'px'
			}">跳过{{time}}s</view>
		</view>
		<template v-else>
			<u-navbar :is-back="false" :border-bottom="false">
				<view class="nav-title" @click="getAuthorization">
					<u-icon name="map" size="34"></u-icon>
					<text>{{street}}</text>
				</view>
			</u-navbar>

			<template v-if="authorizationState && mapLongitude != ''">

				<map enable-overlooking enable-3D @markertap="markertap" show-location @regionchange="regionchange" :style="{height:mapHeight}"
				 :markers="markers" :longitude="mapLongitude" :latitude="mapLatitude"></map>

				<view class="nav">
					<swiper @change="change" next-margin="150rpx" :current="current">
						<swiper-item v-for="(item,index) in markers" :key="index">
							<view class="swiper-item">
								<u-image @click="previewUserHead(item.userPhoto)" width="90" height="90" border-radius="10" :src="item.userPhoto"></u-image>
								<view class="info">
									<view class="">{{item.nickName}}</view>
									<view class="">距离您{{item.distance}}</view>
								</view>
							</view>
						</swiper-item>
					</swiper>
					<view class="safe-area-inset-bottom"></view>
				</view>
			</template>
			<template v-if="authorizationState && mapLongitude == ''">
				<view class="loading">
					<u-loading></u-loading>
				</view>
			</template>
			<template v-if="!authorizationState">
				<view class="empty">
					<u-empty mode="permission" text="暂无权限"></u-empty>
				</view>
			</template>
			<u-modal show-cancel-button confirm-color="#FE4666" v-model="show" @confirm="confirm" :content="content"></u-modal>
		</template>
		<!-- <view class="tabbar">
			<u-tabbar :before-switch="tabChange" :show="tabBarState && !banner" inactive-color="#A5A4A4" active-color="#333333"
			 icon-size="36" :list="tabBarList" mid-button mid-button-size="104" :border-top="false">
			</u-tabbar>
		</view> -->
	</view>
</template>

<script>
	import QQMapWX from "@/common/qqmap-wx-jssdk.min";
	import WSCoordinate from '@/js_sdk/WSCoordinate'
	let qqmapsdk = ''
	export default {
		onShareAppMessage() {
			return {
				title: '微谷社交，您的智慧生活管家',
				path: '/pages/tabBar/sceneSocialContact/sceneSocialContact?userId=' + uni.getStorageSync(
					'userInfo').id,
				imageUrl: this.imageURL + 'USER/bd408063-b1af-4cbc-a29f-d0ebe6a26357.png'
			}
		},
		onShareTimeline() {
			return {
				title: '微谷社交，您的智慧生活管家',
				path: '/pages/tabBar/sceneSocialContact/sceneSocialContact?userId=' + uni.getStorageSync(
					'userInfo').id,
				imageUrl: this.imageURL + 'USER/bd408063-b1af-4cbc-a29f-d0ebe6a26357.png'
			}
		},
		data() {
			return {
				tabBarState: false,
				btnOffset: uni.getSystemInfoSync().statusBarHeight + 44,
				top: 0,
				loading: true,
				readyImgURL: this.imageURL + 'USER/a7be8a46-2535-4843-b7ef-f27d052c8c1c.png',
				time: 5,
				// tabBarList: [{
				// 		"pagePath": "/pages/tabBar/index/index",
				// 		"iconPath": "/static/index-tab.png",
				// 		"selectedIconPath": "/static/index-tabActive.png",
				// 		"text": "抢购商城"
				// 	},
				// 	{
				// 		"pagePath": "/pages/tabBar/shop/shop",
				// 		"iconPath": "/static/shop-tab.png",
				// 		"selectedIconPath": "/static/shop-tabActive.png",
				// 		"text": "附近店铺",
				// 	},
				// 	{
				// 		iconPath: "/static/main-tab-bar-icon.png",
				// 		selectedIconPath: "/static/main-tab-bar-icon.png",
				// 		pagePath: "/pages/tabBar/sceneSocialContact/sceneSocialContact",
				// 		midButton: true
				// 	},
				// 	{
				// 		"pagePath": "/pages/tabBar/order/order",
				// 		"iconPath": "/static/order-tab.png",
				// 		"selectedIconPath": "/static/order-tabActive.png",
				// 		"text": "我的订单"
				// 	},
				// 	{
				// 		"pagePath": "/pages/tabBar/my/my",
				// 		"iconPath": "/static/my-tab.png",
				// 		"selectedIconPath": "/static/my-tabActive.png",
				// 		"text": "个人中心"
				// 	}
				// ],
				current: null,
				mapLongitude: '',
				banner: uni.getStorageSync('jumpBanner') ? false : true,
				mapLatitude: '',
				show: false,
				mapHeight: uni.getSystemInfoSync().windowHeight - (94 + uni.getSystemInfoSync().safeAreaInsets.bottom + uni.getSystemInfoSync()
					.statusBarHeight) + 'px',
				longitude: 0,
				latitude: 0,
				content: '检测到您没打开获取信息功能权限， 是否去设置打开？',
				authorizationState: uni.getStorageSync('locationPermission') ? true : false,
				street: '正在定位...',
				markers: [],
				backTextStyle: {
					color: '#000000'
				}
			};
		},
		onReady() {
			// this.$nextTick(() => {
			// 	this.tabBarState = true
			// })
		},
		onLoad(options) {
			if (options.userId) {
				if (!uni.getStorageSync('userInfo')) {
					uni.setStorageSync('proUserId', options.userId)
				}
			}
			this.pageNo = 1
			qqmapsdk = new QQMapWX({
				key: 'HQSBZ-EMKE5-6N5IW-QYGDQ-U6EMS-P2BOO'
			});
			if (!this.banner) {
				uni.setNavigationBarColor({
					frontColor: '#000000',
					backgroundColor: ''
				})
				this.init((res, lat, lng) => {
					this.mapLongitude = lng
					this.mapLatitude = lat
				})
			} else {
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: ''
				})
				this.timer = setInterval(() => {
					this.time--
					if (this.time <= 0) {
						clearInterval(this.timer)
						this.jump()
					}
				}, 1000)
			}
		},
		methods: {
			previewUserHead(url) {
				if (url == '/static/team-head-img.png') {
					uni.showToast({
						title: '该用户有点神秘，无法查看该头像',
						icon: 'none'
					});
					return
				}
				uni.previewImage({
					urls: [url]
				})
			},
			load() {
				this.loading = false
			},
			tabChange(index) {
				if (index == 3 || index == 4) {
					if (uni.getStorageSync('userInfo')) {
						return true
					} else {
						this.$u.route('/pages/user/login/login')
						return false
					}
				} else {
					return true
				}
			},
			jump() {
				this.top = uni.getSystemInfoSync().screenHeight
				clearInterval(this.timer)
				setTimeout(() => {
					this.banner = false
					uni.setStorageSync('jumpBanner', true)
					uni.setNavigationBarColor({
						frontColor: '#000000',
						backgroundColor: ''
					})
					this.init((res, lat, lng) => {
						this.mapLongitude = lng
						this.mapLatitude = lat
					})
				}, 300)
			},
			updateStreet(longitude, latitude) {
				const self = this
				qqmapsdk.reverseGeocoder({
					location: {
						longitude: longitude, //经度
						latitude: latitude //纬度
					},
					success(res) {
						if (res.status == 0) {
							let {
								result
							} = res, {
								address_component
							} = result
							let street = address_component.street
							if (street.length > 7) {
								street = street.substring(0, 7) + "...";
							}
							self.authorizationState = true
							self.street = street
						} else {
							self.street = '定位失败'
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					}
				})
			},
			markertap(e) {
				this.current = e.target.markerId
				this.markers.forEach(item => {
					item.iconPath = item.type == 1 ? '/static/map-store.png' : '/static/map-user.png'
				})
				this.markers[this.current].iconPath = this.markers[this.current].type == 1 ? '/static/map-store-active.png' :
					'/static/map-user-active.png'
				this.updateStreet(this.markers[this.current].longitude, this.markers[this.current].latitude)
			},
			change(e) {
				let currentMarker = this.markers[e.detail.current]
				// let newResult = WSCoordinate.transformFromWGSToGCJ(currentMarker.latitude, currentMarker.longitude);
				// let BD_Coordinate = WSCoordinate.transformFromGCJToBaidu(newResult.latitude, newResult.longitude)
				this.mapLongitude = currentMarker.longitude
				this.mapLatitude = currentMarker.latitude
				this.current = e.detail.current
				this.markers.forEach(item => {
					item.iconPath = item.type == 1 ? '/static/map-store.png' : '/static/map-user.png'
				})
				this.markers[this.current].iconPath = this.markers[this.current].type == 1 ? '/static/map-store-active.png' :
					'/static/map-user-active.png'
				this.updateStreet(this.markers[this.current].longitude, this.markers[this.current].latitude)
			},
			regionchange(e) {
				this.$u.debounce(() => {
					const self = this
					if (e.type == 'end' && e.causedBy == 'drag') {
						let BD_Coordinate = WSCoordinate.transformFromGCJToBaidu(e.target.centerLocation.latitude,e.target.centerLocation.longitude)
						let latitude = BD_Coordinate.latitude,
							longitude = BD_Coordinate.longitude
						qqmapsdk.calculateDistance({
							to: `${e.target.centerLocation.latitude},${e.target.centerLocation.longitude}`,
							success(res) {
								if (res.status == 0) {
									let {
										result
									} = res
									let distance = result.elements[0].distance
									if (distance > 1000) {
										let kilometre = (Math.round(distance / 100) / 10).toFixed(1)
										if (Number(kilometre) >= 1) {
											self.getLocation(self.latitude, self.longitude, latitude, longitude)
											self.moveLat = latitude
											self.moveLng = longitude
										}
									}
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none'
									})
								}
							}
						})
					}
				}, 300)
			},
			confirm() {
				const self = this
				uni.openSetting({
					success: (res) => {
						self.authorizationState = true
						self.init((res, lat, lng) => {
							self.mapLongitude = lng
							self.mapLatitude = lat
						})
					}
				})
			},
			getLocation(latitude, longitude, userLatitude, userLongitude) {
				const self = this
				self.$u.post('user/location/nearByLocationList', {
					// pageNo: this.pageNo,
					// pageSize: this.next ? 10 : '',
					latitude: latitude,
					longitude: longitude,
					queryDistance: 900,
					userLatitude: userLatitude,
					userLongitude: userLongitude,
				}).then(res => {
					uni.showLoading({
						title: '正在加载...'
					})
					let markers
					markers = res.list.map((item, index) => {
						let userPhoto = item.photo
						if (userPhoto && item.photo != 'null') {
							if (userPhoto.indexOf(self.imageURL) == -1) {
								if (userPhoto.indexOf('https://thirdwx.qlogo.cn') == -1) {
									userPhoto = self.imageURL + userPhoto
								}else{
									
								}
							}
						} else {
							userPhoto = '/static/team-head-img.png'
						}
						let GCJ_Coordinate = WSCoordinate.transformFromBaiduToGCJ(item.latitude, item.longitude);
						// let WGS_Coordinate = WSCoordinate.transformFromGCJToWGS(newResult.latitude, newResult.longitude)
						return {
							id: index,
							latitude: GCJ_Coordinate.latitude,
							distance: item.distance < 1000 ? item.distance + '米' : (Math.round(item.distance / 100) / 10).toFixed(1) +
								'公里',
							longitude: GCJ_Coordinate.longitude,
							nickName: item.name && item.name != 'null' ? item.name : '匿名',
							// timestemp: item.timestemp,
							iconPath: index == self.current ? item.type == 1 ? '/static/map-store-active.png' :
								'/static/map-user-active.png' : item.type == 1 ? '/static/map-store.png' : '/static/map-user.png',
							userPhoto: userPhoto,
							width: uni.upx2px(58),
							type:item.type,
							height: uni.upx2px(58)
						}
					})
					self.markers = [...markers]
					self.$nextTick(() => {
						uni.hideLoading()
					})
				}).catch(error => {
					console.log(error);
				})
			},
			reportingPosition() {
				if (!uni.getStorageSync('userInfo')) return
				this.$u.post('user/location/reportLocation', {
					longitude: this.longitude,
					latitude: this.latitude,
					nickName: uni.getStorageSync('userInfo').nickName,
					userPhoto: uni.getStorageSync('userInfo').headPhoto
				}).then(res => {
					this.getLocation(this.latitude, this.longitude, this.moveLat || this.latitude, this.moveLng || this.longitude)
				})
			},
			init(call = () => {}) {
				const self = this
				//#ifdef MP-WEIXIN
				uni.getLocation({
					type: 'gcj02',
					altitude: true,
					success(res) {
						let BD_Coordinate = WSCoordinate.transformFromGCJToBaidu(res.latitude, res.longitude)
						self.longitude = BD_Coordinate.longitude
						self.latitude = BD_Coordinate.latitude
						call(BD_Coordinate, res.latitude, res.longitude)
						self.updateStreet(res.longitude, res.latitude)
						uni.setStorageSync('locationPermission', {
							longitude: res.longitude,
							latitude: res.latitude
						})
						if (uni.getStorageSync('reportingStatus')) {
							self.getLocation(self.latitude, self.longitude, self.latitude, self.longitude)
						} else {
							self.reportingPosition()
							setInterval(self.reportingPosition, 1000 * 60 * 5)
						}
					},
					fail(e) {
						self.authorizationState = false
						self.street = '重新定位'
						if (uni.getStorageSync('locationPermission')) {
							uni.removeStorageSync('locationPermission')
						}
					}
				})
				//#endif

				//#ifdef H5
				self.longitude = 114.24779
				self.latitude = 22.71991
				self.mapLongitude = self.longitude
				self.mapLatitude = self.latitude
				self.authorizationState = true
				self.getLocation(self.latitude, self.longitude, self.latitude, self.longitude)
				//#endif
			},
			getAuthorization() {
				const self = this
				if (!this.authorizationState) {
					uni.authorize({
						scope: "scope.userLocation",
						success: (res) => {
							self.authorizationState = true
							self.init((res, lat, lng) => {
								self.mapLongitude = lng
								self.mapLatitude = lat
							})
						},
						fail: (res) => {
							self.show = true
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.loading-img {
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.loading {
		display: flex;
		justify-content: center;
	}

	.tabbar {
		height: 50px;
		overflow: hidden;
	}

	.reday {
		position: fixed;
		bottom: 0;
		transition: all .3s;
		z-index: 999;
		left: 0;
		width: 100%;
		height: 100%;

		image {
			width: 100%;
			height: 100%;
		}

		.btn {
			position: absolute;
			color: #FFFFFF;
			font-size: 30rpx;
			line-height: 50rpx;
			padding: 0 30rpx;
			right: 30rpx;
			background-color: rgba($color: #000000, $alpha: .2);
			border-radius: 24px;
		}
	}

	.empty,
	.loading {
		padding-top: 200rpx;
	}

	.nav {
		position: fixed;
		bottom: 50px;
		left: 0;
		width: 100%;
		z-index: 1;

		swiper {
			height: 170rpx;

			swiper-item {
				padding: 0 30rpx;
				box-sizing: border-box;
			}

			.swiper-item {
				background-color: #FFFFFF;
				box-shadow: 1px 20px 30px 0px rgba(165, 164, 165, 0.36);
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				padding: 20rpx;

				.info {
					margin-left: 20rpx;
					flex: 1;

					view {
						&:first-child {
							font-size: 28rpx;
						}

						&:last-child {
							margin-top: 5rpx;
							font-size: 24rpx;
							color: #AAAAAA;
						}
					}
				}
			}
		}
	}

	map {
		width: 750rpx;
	}

	.nav-title {
		position: absolute;
		// width: 138px;
		width: 170px;
		left: 375rpx;
		transform: translateX(-50%);
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;

		text {
			font-size: 16px;
			font-weight: 700;
			// font-weight: bold;
			margin-left: 15rpx;
		}
	}
</style>
